package com.depth.viewer.utils
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class TimerLoop
	{
		private var _minIndex:int;
		private var _maxIndex:int;
		private var _delay:int = 1;
		private var _scope:int = 1;
		private var _handler:Function;
		private var _timer:Timer;
		private var _currentIndex:int;
		private var _looping:Boolean;
		/**
		 * 由于存在 15 秒执行限制，对于大任务，采用任务队列的方式执行
		 */
		public function TimerLoop(handler:Function = null)
		{
			this._handler = handler;
			_timer = new Timer(10);
			_timer.addEventListener(TimerEvent.TIMER,timerHandler);
		}
		public function set minIndex(value:int):void{
			_minIndex = value;
		}
		public function set maxIndex(value:int):void{
			_maxIndex = value;
		}
		protected function timerHandler(e:TimerEvent):void{
			if(_handler){
				_timer.stop();
				
				var count:int = _maxIndex - _currentIndex;
				count -= 1;
				if(count >= _scope){
					count = _scope;
				}
				_handler(_currentIndex,count);
				
				_timer.start();
			}
			
			_currentIndex += _scope;
			
			if(_currentIndex >= _maxIndex){
				stop();
			}
		}
		public function set loopHandler(value:Function):void{
			this._handler = value;
		}
		public function set delay(value:int):void
		{
			_delay = value;
		}
		public function get delay():int
		{
			return _delay ;
		}

		public function get currentIndex():int
		{
			return _currentIndex;
		}
		public function start():void{
			_timer.delay = _delay;
			_currentIndex = _minIndex;
			_looping = true;
			_timer.start();
		}
		public function stop():void{
			_currentIndex = _minIndex;
			_looping = false;
			_timer.stop();
			_timer.reset();
		}

		public function get looping():Boolean
		{
			return _looping;
		}

		public function set scope(value:int):void
		{
			_scope = value;
		}
		public function get scope():int
		{
			return _scope;
		}

	}
}